<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">商品管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许选择三级分类相关参数" type="warning" show-icon :closable="false"></el-alert>
      <div>
        <span>请选择分类：</span>
        <el-cascader
          v-model="cascaderKeysId"
          :options="cateList"
          :props="cascaderProps"
          @change="handleCascaderChange"
          clearable
        ></el-cascader>
      </div>
      <!-- tab标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--动态参数面板  -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="add">添加参数</el-button>
          <!-- 表格 -->
          <el-table :data="manyTabData" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable class="elTagMargin" v-for="(item, index) in scope.row.attr_vals" :key="index" @close='handleTagClose(index,scope.row)'>{{item}}</el-tag>
                <!-- 动态编辑标签，要放在template里面 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--静态参数面板  -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="add">添加属性</el-button>
          <!-- 表格 -->
          <el-table :data="onlyTabData" style="width: 100%" border>
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加的对话框，动态参数和静态属性共用 -->
      <el-dialog :title="'添加'+titleText" :visible.sync="dialogVisible" width="50%">
        <!-- form表单 -->
        <el-form
          :model="addForm"
          :rules="addFormRefRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAddParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑的对话框，动态参数和静态属性共用 -->
      <el-dialog :title="'编辑'+titleText" :visible.sync="editDialogVisible" width="50%">
        <!-- form表单 -->
        <el-form
          :model="editForm"
          :rules="editFormRefRules"
          ref="editFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureEdit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      // 级联选择框选中的值的id
      cascaderKeysId: [],
      // 级联选择框数据渲染的规则
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      activeName: 'many',
      // 动态参数数据
      manyTabData: [],
      // 静态参数数据
      onlyTabData: [],
      // 添加对话框的遍量
      dialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRefRules: {
        attr_name: [
          { required: true, message: '请输入正确值', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 修改对话框的遍量
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRefRules: {
        attr_name: [
          { required: true, message: '请输入正确值', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  mounted () {
    this.getCateList()
  },
  computed: {
    // 通过计算属性，判断级联选择框是否选中，来判断是否禁用面板的里面的添加按钮
    // 也可以直接写表达式，不用计算属性 :disabled="cascaderKeysId.length !== 3"
    isBtnDisabled () {
      if (this.cascaderKeysId.length !== 3) {
        return true
      }
      return false
    },
    // 获取级联选择的值(最后一个值才是需要的)
    cateId () {
      if (this.cascaderKeysId.length === 3) {
        return this.cascaderKeysId[2]
      }
      return null
    },
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
    },
    // 当级联选择的值发生变化时触发
    handleCascaderChange () {
      if (this.cascaderKeysId.length !== 3) {
        this.cascaderKeysId = []
      }
      // 当级联选择框值发生变化的时候就发起数据请求，为下面面板提供数据
      this.getAttrList()
    },
    // 获取所有参数列表
    async getAttrList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // 当级联选择框清空的时候，判断res.data里面是否有值
      if (res.data === null) {
        this.manyTabData = []
        this.onlyTabData = []
        this.$message.error('获取参数失败')
        return
      }
      // 判断当前所选tab是哪个，并把数据保存到不同类别里面去
      if (this.activeName === 'many') {
        res.data.forEach((item) => {
          // 这一步是让每一行都有
          item.inputVisible = false
          item.inputValue = ''
          // 这里循环是因为后台提供的数据是字符串，但是我们需要的是数组，所以把得到的数据修改后重新赋值给原来的数据
          // 这里要判断一下attr_vals的值是不是空，是空就直接返回[]
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTabData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTabData = res.data
      }
    },
    // 点击标签nav的时候
    handleTabClick () {
      this.getAttrList()
    },
    add () {
      this.dialogVisible = true
    },
    // 点击对话框确定的时候，发送提交请求
    async sureAddParams () {
      if (this.activeName === 'many') {
        await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
      } else if (this.activeName === 'only') {
        await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
      }
      this.getAttrList()
      this.dialogVisible = false
    },
    // 编辑按钮
    async edit (info) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${info.attr_id}`,
        {
          params: {
            attr_name: info.attr_name,
            attr_sel: this.activeName
          }
        }
      )
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 提交编辑
    async sureEdit () {
      // 先预验证
      // eslint-disable-next-line no-unused-vars
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      )
      this.getAttrList()
      this.editDialogVisible = false
    },
    // 删除该行参数
    deleteParams () {},
    // 操作动态编辑标签
    async handleInputConfirm (row) {
      // 要判断是否输入的内容是否为空
      // 不然会出现bug，就是空格和回车符号都能提交成功
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // 要先把输入框的内容添加到attr_vals数组中，然后以这个新数据发送请求
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      // 当失去焦点，发送请求，编辑数据提交到数据库
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('提交失败')
    },
    // 动态标签双击后，显示输入框
    showInput (row) {
      // 一定要让每一行的动态标签先显示出来渲染到页面
      // 渲染后才能操作元素
      row.inputVisible = true
      this.$nextTick((_) => {
        // console.log(this.$refs)
        // console.log(this.$refs.saveTagInput)
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签
    async handleTagClose (index, row) {
      var ret = row.attr_vals.splice(index, 1)
      console.log(row.attr_vals, ret)
      // 注意这里的发送请求，删除的是attr_vals里的元素。相当于把这个数组重新更新编辑了，所以请求不一样
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('提交失败')
      this.$message.success('成功')
    }
  }
}
</script>
<style scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-cascader {
  width: 300px;
}
.el-tabs {
  margin: 20px 0;
}
.input-new-tag{
  width: 120px;
}
.elTagMargin{
  margin-right: 20px;
}
</style>
